use "$project_path/data/4_regdata/regdata", clear

// Creating outcomes
gen mstd_diff_m1_ex_corruption = -std_diff_m1_ex_corruption
gen mstd_diff_m1_pub_corruption = -std_diff_m1_pub_corruption
egen diff_m1_chix_corruption = rowmean(std_diff_m1_accountability mstd_diff_m1_ex_corruption mstd_diff_m1_pub_corruption std_diff_m1_control_corruption)

log using "$project_path/output/appendix_tables/Appendix_Table_E11.smcl", replace

** Column 1: Baseline
rdrobust std_diff_m1_accountability runvar
rdrobust mstd_diff_m1_ex_corruption runvar
rdrobust mstd_diff_m1_pub_corruption runvar
rdrobust std_diff_m1_control_corruption runvar
rdrobust diff_m1_chix_corruption runvar

** Column 2: Presidential elections
rdrobust std_diff_m1_accountability runvar if Type_Election=="Presidential"
rdrobust mstd_diff_m1_ex_corruption runvar if Type_Election=="Presidential"
rdrobust mstd_diff_m1_pub_corruption runvar if Type_Election=="Presidential"
rdrobust std_diff_m1_control_corruption runvar if Type_Election=="Presidential"
rdrobust diff_m1_chix_corruption runvar if Type_Election=="Presidential"

** Column 3: Parliamentary elections
rdrobust std_diff_m1_accountability runvar if Type_Election=="Parliamentary"
rdrobust mstd_diff_m1_ex_corruption runvar if Type_Election=="Parliamentary"
rdrobust mstd_diff_m1_pub_corruption runvar if Type_Election=="Parliamentary"
rdrobust std_diff_m1_control_corruption runvar if Type_Election=="Parliamentary"
rdrobust diff_m1_chix_corruption runvar if Type_Election=="Parliamentary"

** Column 4: High checks and balances
rdrobust std_diff_m1_accountability runvar if subsample_high_checks==1
rdrobust mstd_diff_m1_ex_corruption runvar if subsample_high_checks==1
rdrobust mstd_diff_m1_pub_corruption runvar if subsample_high_checks==1
rdrobust std_diff_m1_control_corruption runvar if subsample_high_checks==1
rdrobust diff_m1_chix_corruption runvar if subsample_high_checks==1

** Column 5: Low checks and balances
rdrobust std_diff_m1_accountability runvar if subsample_low_checks==1
rdrobust mstd_diff_m1_ex_corruption runvar if subsample_low_checks==1
rdrobust mstd_diff_m1_pub_corruption runvar if subsample_low_checks==1
rdrobust std_diff_m1_control_corruption runvar if subsample_low_checks==1
rdrobust diff_m1_chix_corruption runvar if subsample_low_checks==1

** Column 6: High leader power
rdrobust std_diff_m1_accountability runvar if subsample_high_power==1
rdrobust mstd_diff_m1_ex_corruption runvar if subsample_high_power==1
rdrobust mstd_diff_m1_pub_corruption runvar if subsample_high_power==1
rdrobust std_diff_m1_control_corruption runvar if subsample_high_power==1
rdrobust diff_m1_chix_corruption runvar if subsample_high_power==1

** Column 7: Low leader power
rdrobust std_diff_m1_accountability runvar if subsample_low_power==1
rdrobust mstd_diff_m1_ex_corruption runvar if subsample_low_power==1
rdrobust mstd_diff_m1_pub_corruption runvar if subsample_low_power==1
rdrobust std_diff_m1_control_corruption runvar if subsample_low_power==1
rdrobust diff_m1_chix_corruption runvar if subsample_low_power==1

log close

/*
This programs tests the equality of two coefficients using the Z-test proposed by https://psycnet.apa.org/record/1995-27766-001
*/
capture program drop equality_test
program define equality_test, rclass
	args est1 est2 se1 se2
	local z = (`est1'-`est2')/sqrt((`se1')^2 + (`se2')^2)
	local pval=2*(1-normal(abs(`z')))
	local formatted_pval : di %6.3f `pval'
    return local formatted_pval = "`formatted_pval'"
end

*** Building .tex table
// Regressions 
#delimit ;
local outcomes  
		std_diff_m1_accountability
		mstd_diff_m1_ex_corruption
		mstd_diff_m1_pub_corruption
		std_diff_m1_control_corruption
		diff_m1_chix_corruption
;
#delimit cr		

local subsample_count 7

// Initialize matrix of results and define value labels
local ncols = `subsample_count'*2
local nrows = 10
//Prepare matrix of coefficients and other statistics
mat Coefs = J(`nrows', `ncols', .)

mat list Coefs

local type_election Presidential Parliamentary
local subsamples "_high_checks _low_checks _high_power _low_power"

//inizialize indices
local row = 1
local next_row = `row' + 1

foreach v in `outcomes'{
	//Initialize indices
	local col = 1
	local pval_col = `subsample_count' + 1

	rdrobust `v' runvar, all
	
	//Store estimates and stats
	local b_`col': di %5.3f e(tau_cl)
	local se_`col': di %5.3f e(se_tau_rb)
	local p_`col': di %5.3f e(pv_rb)

	mat Coefs[`row',`col'] = `b_`col''
	mat Coefs[`next_row',`col'] = `se_`col''
	mat Coefs[`row',`pval_col'] = `p_`col''
	
	foreach type in `type_election'{
		
		local ++col	
		local ++pval_col
		rdrobust `v' runvar if Type_Election == "`type'", all
		
		//Store estimates and stats
		local b_`col': di %5.3f e(tau_cl)
		local se_`col': di %5.3f e(se_tau_rb)
		local p_`col': di %5.3f e(pv_rb)
		local N_`col': di %6.0f e(N)
	
		mat Coefs[`row',`col'] = `b_`col''
		mat Coefs[`next_row',`col'] = `se_`col''
		mat Coefs[`row',`pval_col'] = `p_`col''	

	}
	
	
	foreach sub in `subsamples'{
		
		local ++col	
		local ++pval_col
		rdrobust `v' runvar if subsample`sub' == 1, all
		
		//Store estimates and stats
		local b_`col': di %5.3f e(tau_cl)
		local se_`col': di %5.3f e(se_tau_rb)
		local p_`col': di %5.3f e(pv_rb)
	
		mat Coefs[`row',`col'] = `b_`col''
		mat Coefs[`next_row',`col'] = `se_`col''
		mat Coefs[`row',`pval_col'] = `p_`col''	
		
	}
	
	local row = `row' + 2
	local next_row = `row' + 1
}

equality_test Coefs[9,2] Coefs[9,3] Coefs[10,2] Coefs[10,3]
local chix_corr_eq_pval_pres_parl = r(formatted_pval)
equality_test Coefs[9,4] Coefs[9,5] Coefs[10,4] Coefs[10,5]
local chix_corr_eq_pval_checks = r(formatted_pval)
equality_test Coefs[9,6] Coefs[9,7] Coefs[10,6] Coefs[10,7]
local chix_corr_eq_pval_power = r(formatted_pval)

mat list Coefs

********************************************************************************
* 								EXPORT TABLE
********************************************************************************			
	// Clear the dataset, and use the matrix as dataset			

	clear
	svmat Coefs

	//	input variable names
	gen varname = ""
	gen temp = _n
	replace varname = "Government accountability index" if temp == 1
	replace varname = "SE_1" if temp == 2
	replace varname = "(Minus) Executive corruption index" if temp == 3
	replace varname = "SE_2" if temp == 4
	replace varname = "(Minus) Public sector corruption index" if temp == 5
	replace varname = "SE_3" if temp == 6
	replace varname = "Control of corruption" if temp == 7
	replace varname = "SE_4" if temp == 8
	replace varname = "Absence of corruption index" if temp == 9
	replace varname = "SE_5" if temp == 10
	
	order varname, first
	drop temp
	  
	//Adjust the table before exporting
	replace varname = "" if strpos(varname, "SE_")>0
	order varname
	
	// Rename cols and labels
	forvalues n = 1/`subsample_count'{
		rename Coefs`n' Model`n'
	}
	//Cols where we store pvalues
	local n_min = `subsample_count' + 1
	local n_max = `subsample_count'*2
	local i = 1
	forvalues n = `n_min'/`n_max'{
		rename Coefs`n' P_Model`i'
		local ++i
	}
	
	label var varname ""
	label var Model1 "Baseline"
	label var Model2 "Pres."
	label var Model3 "Parl."
	label var Model4 "High"
	label var Model5 "Low"
	label var Model6 "High"
	label var Model7 "Low"
	
		
	// Convert to string and add options
	forvalues i = 1/`subsample_count'{
		tostring Model`i', replace force format(%04.3f)
		replace Model`i'= "" if Model`i'=="."
		//Add parenthesis to SE and P-val
		replace Model`i' = "(" + Model`i' + ")" if missing(varname) & Model`i' !=""	

	}
	
	// Add stars
	local 3_star 0.01
	local 2_star 0.05
	local 1_star 0.10
	
	forvalues i = 1/`subsample_count'{
		
		replace Model`i' = Model`i' + "***" if P_Model`i' < `3_star'
		replace Model`i' = Model`i' + "**" if P_Model`i' < `2_star' & P_Model`i' > `3_star'
		replace Model`i' = Model`i' + "*" if P_Model`i' < `1_star' & P_Model`i' > `2_star'
		
		drop P_Model`i'
	}
	
	foreach var of varlist _all {
	qui replace `var' = ustrtrim(`var')	
}


local title = "Effects of electoral turnovers on governance and corruption"
local filename = "baseline_het_corruption"
local output "$project_path/output/appendix_tables/Appendix_Table_E11.tex"
local headerlines = " & &  \multicolumn{2}{c}{\textbf{Election type}} & \multicolumn{2}{c}{\textbf{Checks \& balances}} & \multicolumn{2}{c}{\textbf{Leader power}}"
local footnote = "\caption*{\footnotesize \emph{Notes}: This table reports RD estimates corresponding to equation (\ref{eq:baseline_rdd}) for our measures of governance and corruption, expressed in standard deviation terms, in the main sample (column 1) and in different subsamples (columns 2 to 7). See Table \ref{tab:baseline_het_pres_parl_ballot} for the definition of the high and low checks and balances subsamples, and Appendix Table \ref{tab:baseline_het_global_checks_power} for the definition of high and low leader power subsamples. Using the method of \cite{clogg1995statistical}, we can reject the equality of the estimates for the absence of corruption index for presidential and parliamentary elections (p-val. = `chix_corr_eq_pval_pres_parl'), but not for high and low checks and balances (p-val. = `chix_corr_eq_pval_checks'), and for high and low leader power (p-val. = `chix_corr_eq_pval_power'). We obtain broadly consistent results when running a parametric regression in which we include the interaction between the treatment and the dimension of heterogeneity. $^{*} p<0.10,^{**} p<0.05,^{***} p<0.01$.}"

	texsave using "`output'", replace title("`title'") varlabels noendash ///
							  footnote("`footnote'") ///
							  headerlines("`headerlines'" "& (1) & (2) & (3) & (4) & (5) & (6) & (7)") ///
							  frag nofix marker("tab:`filename'") location(H)
	

	
